<?php
/**
 * Created by PhpStorm.
 * User: Anders
 * Date: 2018/12/22
 * Time: 9:36
 */

use App\Models\Role;
use App\Models\User;

/**
 * 公共函数库
 */
if (!function_exists('st')) {
    function st($param)
    {
        return 'http://www.test.com/' . $param;
    }
}

function subMenu(array $data, int $pid = 0, int $level = 0)
{
    static $arr = [];
    foreach ($data as $item) {
        if ($item['pid'] == $pid) {
            $item['lv'] = $level + 1;
            $arr[] = $item;
            subMenu($data, $item['id'], $item['lv']);
        }
    }
    return $arr;
}

if (!function_exists('subTree')) {
    function subTree(array $data, int $pid = 0)
    {
        $arr = [];
        foreach ($data as $val) {
            if ($val['pid'] == $pid) {
                $val['sub'] = subTree($data, $val['id']);
                $arr[] = $val;
            }
        }
        return $arr;
    }
}

/**
 * 验证是否可以访问当前路由
 * @param $request
 * @return bool
 */
function checkRoute($request)
{
    $username = auth()->user()->username;
//    admin用户不需要检测
    if ($username == 'admin') return true;
    $role_id = User::with('role')->where('username', $username)->first()->role_id;
    //权限可以访问的路由别名
    if (!$permissions = Role::with('permissions')->where('id', $role_id)->first()) {
        $route_list = [];
    } else {
        $permissions = $permissions->permissions->toArray();
        $route_list = array_column($permissions, 'route');
    }
    //再加上白名单路由别名
    $white_list = config('whitelist');
    $route_list = array_merge($route_list, $white_list);
    //当前访问路由别名
    $route = $request->route()->getAction()['as'];
    //dump($route_list);dump($route);
    // 返回错误页面
    return array_search($route, $route_list) !== false ? true : false;
}

/**
 * CURL请求
 * @param string $url 请求的URL地址
 * @param array $content 发送的数据
 * @param string $file 发送的文件路径
 * @return mixed
 */
function curl_request(string $url, array $content = [], string $file = '')
{
    if (!empty($file)) {
        $content['file'] = new CURLFile($file);
    }
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HEADER, 0);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_TIMEOUT, 10);
    curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36');
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
    if (!empty($content)) {
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $content);
    }
    $res = curl_exec($curl);
    curl_close($curl);
    return $res;
}